package org.lightmtv.request;

import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class ServletHttpRequest extends RequestBean{
	
	private HttpServletRequest servletRequest;
	
	@SuppressWarnings("deprecation")
	public ServletHttpRequest(HttpServletRequest servletRequest) {
		super();
		this.servletRequest = servletRequest;
		try {
			servletRequest.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e1) {
		}
		setPath(servletRequest.getServletPath());
		
		Map<String, String> params = new LinkedHashMap<String, String>();
		Map<String, FileUpload> uploads = new LinkedHashMap<String, FileUpload>();
		
		if(ServletFileUpload.isMultipartContent(servletRequest)){
//		==== File Uploading 
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			
			upload.setHeaderEncoding("UTF-8");
			try{
				List<FileItem> items = upload.parseRequest(servletRequest);
				for(FileItem item : items){
					String name = item.getFieldName();
					if(item.isFormField()){
						String value = item.getString("UTF-8");
						params.put(name, value);
					}else{
						uploads.put(name, new CommonsFileUpload(item));
					}
				}
			}catch(Throwable t){
			}
		}else{
			for(Enumeration e = servletRequest.getParameterNames();e.hasMoreElements();){
				String name = (String) e.nextElement();
				String value = servletRequest.getParameter(name);
				params.put(name, value);
			}
		}
		//process header
		Map<String, String> headers = new HashMap<String, String>();
		Enumeration e=servletRequest.getHeaderNames();
		while(e.hasMoreElements()){
			String name = (String) e.nextElement();
			String value = servletRequest.getHeader(name);
			headers.put(name, value);
		}
		setHeaders(headers);
		//process cookie
		setCookies(servletRequest.getCookies());
		
		setContextPath(servletRequest.getContextPath());
		setParams(params);
		setUploads(uploads);
	}
	
	@Override
	public Locale getBestLocaleIn(Locale[] avariableLocles) {
		// TODO 实现父类的方法，删除此方法
		return getServletRequest().getLocale();
	}
	
	@Override
	public void setSession(HttpSession session) {
	}
	
	@Override
	public HttpSession getSession() {
		return this.servletRequest.getSession();
	}
	
	@Deprecated
	public HttpServletRequest getServletRequest() {
		return servletRequest;
	}
	
	public String getMethod(){
		return servletRequest.getMethod();
	}
}
